<template>
  <div class="common-body">
    <!-- 面包屑 -->
    <breadcrumb
      :breadcrumbArr="breadcrumbArr"
      :breadcrumbLastItem="breadcrumbLastItem"
      state="detail"
      @handleBack="handleBack"
    />

    <div
      :class="[
        contractState ? 'ccui-app-container-detail' : 'detail-box',
        'ccui-clearfix'
      ]"
      v-if="isTrue"
    >
      <!--  主体左侧内容  -->
      <div :class="[!contractState ? 'detail-info' : '']">
        <!--  审批状态 icon  -->
        <div v-if="!contractState" class="detail-info-el-Label">
          <el-label :type="approving" v-if="approvingStatus"></el-label>
        </div>
        <div
          :class="[
            !contractState
              ? 'detail-info-form-container'
              : 'ccui-app-container-detail-body'
          ]"
        >
          <el-tabs v-model="activeName" class="el-tabs__customize">
            <el-tab-pane label="基本信息" name="a">
              <el-group-title class="d_jump">
                <template slot="groupTitle">
                  <basicInfoDetail
                    :basic-info="basicInfo"
                    :basic-info-obj="basicInfoObj"
                  />
                </template>
              </el-group-title>
            </el-tab-pane>

            <el-tab-pane label="结算单明细" name="b">
              <div class="ccui-multifunctional-table-wrapper">
                <el-table
                  :data="showTableData"
                  max-height="525"
                  ref="tableList"
                  border
                  :summary-method="getSummaries"
                  show-summary
                >
                  <el-table-column
                    v-for="(item, i) in tableColumnList"
                    :label="item.label"
                    :fixed="item.fixed"
                    :type="item.type"
                    :prop="item.prop"
                    :header-align="item.headerAlign || 'left'"
                    :align="item.align"
                    :min-width="item.width"
                    :key="i"
                    :show-overflow-tooltip="true"
                  >
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>

            <!-- <el-tab-pane label="验收单明细" name="c">
              <div class="ccui-multifunctional-table-wrapper">
                <el-table
                  :data="showTableData1"
                  max-height="525"
                  ref="tableList"
                  border
                  show-summary
                  :summary-method="getSummaries1"
                >
                  <el-table-column
                    v-for="(item, i) in tableColumnList1"
                    :label="item.label"
                    :fixed="item.fixed"
                    :type="item.type"
                    :prop="item.prop"
                    :header-align="item.headerAlign || 'left'"
                    :align="item.align"
                    :min-width="item.width"
                    :key="i"
                    :show-overflow-tooltip="true"
                  >
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane> -->

            <el-tab-pane label="附件" name="d" class="file-group">
              <fileInfo
                ref="fileInfo"
                v-if="isTrue"
                v-model="fileList"
                state="detail"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <!--  右边审批状态  -->
      <approval-read-record
        v-if="!contractState"
        :approvalRecordData="approvalRecordData"
      />
    </div>

    <returnDialog ref="returnDialog" @getValue="getValue" />

    <!--  底部导航栏及签名导出  -->
    <bottomGuide
      v-if="isTrue"
      busiType="120"
      pageType="exportSettleEquip"
      exportMethod="get"
      methodGetPageType="exportSettleEquip"
      :approvalStatus="approving"
      :curPageId="$route.params.id"
      @handleBack="handleBack"
    >
      <template slot="start">
        <li>
          <el-button
            v-if="
              basicInfoObj.supplierBillStatus == 3 &&
              ['2', '4', '6'].includes(basicInfoObj.settlementStatus)
            "
            type="bottom"
            icon="icon-ccui-export"
            @click="openReturnDialog"
            >退回供应商
          </el-button>
        </li>
        <li>
          <el-button
            v-if="
              basicInfoObj.supplierBillStatus == 3 &&
              ['2', '4', '6'].includes(basicInfoObj.settlementStatus)
            "
            type="bottom"
            icon="icon-ccui-export"
            @click="handleCommit"
            >保存并提交
          </el-button>
        </li>
      </template>
    </bottomGuide>
  </div>
</template>

<script>
import basicInfoDetail from "@/basa/components/public_practice/basicInfoDetail";
import publicComponent from "@/basa/components/public";
import fileInfo from "@/basa/components/public/uploadInfo3";
import returnDialog from "@/app/settlement-management/settlement-maintenance-approval/components/returnDialog";
import {
  getById,
  sendBackToSupplier,
  submitSettlement
} from "@/app/settlement-management/material-rent/api";
import BigNumber from "bignumber.js";

export default {
  name: "item_detail",
  components: {
    basicInfoDetail,
    fileInfo,
    breadcrumb: publicComponent.breadcrumb,
    bottomGuide: publicComponent.bottomGuide,
    approvalReadRecord: publicComponent.approvalRecord,
    returnDialog
  },
  data() {
    return {
      activeName: "a",
      businessCode: "",
      breadcrumbLastItem: "",
      // 面包屑导航
      breadcrumbArr: [
        {
          path: "/settlement-management/settlement-maintenance-approval/settlement-maintenance-all",
          text: "结算管理"
        },
        {
          path: "/settlement-management/material-rent-preserve/ListAll",
          text: "周材租赁结算管理"
        },
        {
          path: "/settlement-management/material-rent-preserve/ListAll",
          text: "结算单维护"
        }
      ],
      contractState: "",
      approvalRecordData: [],
      approving: "", // 审批状态
      approvingStatus: true, // 审批状态展示
      approvingType: {
        1: "approving", // 审批中
        2: "withdrawn", // 已撤回
        3: "approvaled", // 审批通过
        4: "sendback", // 审批退回
        5: "unapproval" // 审批不通过
      },
      isTrue: false,
      basicInfo: [
        {
          label: "填报单位",
          value: "reportInOrgName"
        },
        {
          label: "结算期间",
          value: "settlements"
        },
        {
          label: "结算单名称",
          value: "settlementName"
        },
        {
          label: "结算单编号",
          value: "settlementCode"
        },
        {
          label: "合同编号",
          value: "contractCode"
        },
        {
          label: "合同名称",
          value: "contractName"
        },
        {
          label: "合同正式编号",
          value: "formalContractCode"
        },
        {
          label: "合同金额",
          value: "contractMoney"
        },
        {
          label: "供应商",
          value: "supplierName",
          colSpan: 24
        },
        {
          label: "结算数量",
          value: "currSetCount"
        },
        {
          label: "结算金额",
          value: "currSetMoney"
        },
        {
          label: "编制人",
          value: "reportUsername"
        },
        {
          label: "编制日期",
          value: "reportTime"
        },
        {
          label: "备注",
          value: "remarks",
          colSpan: 22,
          remarkClass: true,
          title: true
        }
      ],
      basicInfoObj: {},
      tableData: [],
      showTableData: [],
      tableColumnList: [
        {
          type: "index",
          label: "序号",
          fixed: "left",
          width: "55"
        },
        {
          label: "设备物资编码",
          prop: "materialCode",
          width: "110",
          fixed: true
        },
        {
          label: "设备物资名称",
          prop: "materialName",
          width: "300",
          fixed: true
        },
        // {
        //   label: "验收单编号",
        //   prop: "acceptCode",
        //   width: "130"
        // },
        // {
        //   label: "设备型号说明",
        //   prop: "materialState",
        //   width: "130"
        // },
        {
          label: "规格型号",
          prop: "measureUnit",
          width: "90"
        },
        {
          label: "分类名称",
          prop: "measureUnit",
          width: "90"
        },
        {
          label: "计量单位",
          prop: "measureUnit",
          width: "90"
        },
        {
          label: "结算开始日期",
          prop: "acceptTime",
          width: "100"
        },
        {
          label: "结算截止日期",
          prop: "acceptTime",
          width: "100"
        },
        // {
        //   label: "验收日期",
        //   prop: "acceptTime",
        //   width: "100"
        // },
        // {
        //   label: "剩余可结算数量",
        //   prop: "unTransportCount",
        //   width: "130"
        // },
        {
          label: "结算数量",
          prop: "settlementCount",
          width: "100"
        },
        {
          label: "税率",
          prop: "taxRatePercent"
        },

        {
          label: "含税单价",
          prop: "unitPriceWithTax",
          width: "130"
        },
        {
          label: "含税金额",
          prop: "moneyWithTax",
          width: "130"
        },
        // {
        //   label: "不含税单价",
        //   prop: "unitPriceWithoutTax",
        //   width: "150",
        //   align: "right"
        // },
        // {
        //   label: "不含税金额",
        //   prop: "moneyWithoutTax",
        //   width: "150",
        //   align: "right"
        // },
        // {
        //   label: "生产厂家/品牌",
        //   prop: "brand",
        //   width: "130"
        // }
      ],
      showTableData1: [],
      tableColumnList1: [
        {
          type: "index",
          label: "序号",
          fixed: "left",
          width: "55"
        },
        {
          label: "验收单编号",
          prop: "acceptCode",
          width: "155",
          fixed: true
        },
        {
          label: "验收单名称",
          prop: "acceptName",
          width: "200",
          fixed: true
        },
        {
          label: "验收日期",
          prop: "acceptTime",
          width: "100"
        },
        {
          label: "验收人",
          prop: "acceptor"
        },
        {
          label: "设备物资名称",
          prop: "materialName",
          width: "300"
        },
        {
          label: "设备型号说明",
          prop: "materialState",
          width: "130"
        },
        {
          label: "计量单位",
          prop: "measureUnit"
        },
        {
          label: "合同编号",
          prop: "contractCode",
          width: "150"
        },
        {
          label: "本次结算数量",
          prop: "settlementCount",
          width: "130"
        },
        {
          label: "实际验收数量",
          prop: "acceptCount",
          width: "130"
        },
        {
          label: "结算单价",
          prop: "unitPriceWithTax",
          width: "130",
          align: "right"
        },
        {
          label: "生产厂家/品牌",
          prop: "brand",
          width: "130"
        },
        {
          label: "备注",
          prop: "remarks",
          width: "100"
        }
      ],
      fileList: []
    };
  },
  methods: {
    handleCommit() {
      let params = {
        settlement: this.basicInfoObj,
        settlementList: this.tableData,
        gistUploadIds: this.handleFilesParams().gistUploadIds,
        otherUploadIds: this.handleFilesParams().otherUploadIds,
        isShowPageLoading: true
      };
      submitSettlement(params).then(res => {
        this.$message({
          type: "success",
          message: "保存并提交成功"
        });
        this.handleBack();
      });
    },
    // 退回供应商
    openReturnDialog() {
      this.$refs["returnDialog"].visibleDialog = true;
    },
    // 供应商确定调用退回接口
    getValue(val) {
      let params = {
        id: +this.$route.params.id,
        supplierSendBackReason: val,
        isShowPageLoading: true
      };
      sendBackToSupplier(params).then(res => {
        this.$message({
          type: "success",
          message: res.data.message
        });
        this.handleBack();
      });
    },
    getList() {
      getById({ id: this.$route.params.id, isShowPageLoading: true }).then(
        res => {
          let result = res.data.data;
          this.contractState = !result.approvalRecords.length;
          this.basicInfoObj = result.settlement;
          this.basicInfoObj.currSetCount = this.handleDecimal(
            this.basicInfoObj.currSetCount,
            3
          );
          this.basicInfoObj.contractMoney = this.handleDecimal(
            this.basicInfoObj.contractMoney,
            2
          );
          this.basicInfoObj.currSetMoney = this.handleDecimal(
            this.basicInfoObj.currSetMoney,
            2
          );
          this.basicInfoObj.settlements =
            this.basicInfoObj.settlementStart +
            " 至 " +
            this.basicInfoObj.settlementEnd;
          result.gistFiles.map(e => {
            e.fileType = 51;
            e.fileTypeName = "结算依据";
          });
          result.otherFiles.map(e => {
            e.fileType = 52;
            e.fileTypeName = "其他";
          });
          this.fileList = [...result.gistFiles, ...result.otherFiles];
          this.fileList.sort(this.handleSort("sn"));
          // 含税金额为0时，该行不显示
          this.tableData = res.data.data.settlementList;
          this.tableData.map(item => {
            if (
              item.categoryCode &&
              (item.categoryCode.substr(0, 4) == "1305" ||
                item.categoryCode.substr(0, 4) == "1306" ||
                item.categoryCode.substr(0, 4) == "1307" ||
                item.categoryCode.substr(0, 4) == "1308" ||
                item.categoryCode.substr(0, 4) == "1309" ||
                item.categoryCode.substr(0, 6) == "990103")
            ) {
              this.$set(item, "isCategories", 1);
              this.$set(item, "settlementCount", item.residualSettlementNumber);
            }
            item.unTransportCount = item.unTransportCount
              ? (+item.unTransportCount).toFixed(3)
              : "";
            item.orderCount = item.orderCount
              ? (+item.orderCount).toFixed(3)
              : item.orderNumber
              ? (+item.orderNumber).toFixed(3)
              : "";
            item.acceptCount = item.acceptCount
              ? (+item.acceptCount).toFixed(3)
              : "";
            item.settlementCount = item.settlementCount
              ? (+item.settlementCount).toFixed(3)
              : "";
            item.unitPriceWithTax = item.unitPriceWithTax
              ? (+item.unitPriceWithTax).toFixed(2)
              : "";
            item.unitPriceWithoutTax = item.unitPriceWithoutTax
              ? (+item.unitPriceWithoutTax).toFixed(2)
              : "";
            item.moneyWithTax = (+item.moneyWithTax).toFixed(2);
            item.moneyWithoutTax = (+item.moneyWithoutTax).toFixed(2);
          });

          this.$nextTick(() => {
            this.handleTable(this.basicInfoObj.settlementStatus);
            this.showTableData1 = this.tableData.filter(
              e =>
                e.isMainInventory == 0 &&
                e.isOtherCost == 0 &&
                !e.isCategories &&
                e.acceptCode
            );
          });
          // 审批icon
          this.approvalRecordData = result.approvalRecords;
          this.approvalRecordData.forEach(item => {
            if (item.operState === 0) {
              item.icon = "el-icon-time";
              item.color = "#F5A623";
            }
          });
          this.isTrue = true;
          this.approving = this.approvingType[this.basicInfoObj.approvalStatus];
          this.approvingStatus = false;
          this.$nextTick(() => {
            this.approvingStatus = true;
          });
        }
      );
    },
    // 处理附件入参
    handleFilesParams() {
      let gistUploadIds = [],
        otherUploadIds = [];

      this.fileList.map((e, i) => {
        if (e.fileType == 51) {
          gistUploadIds.push({
            fileDesc: e.fileDesc,
            sn: i,
            uploadId: e.uploadId,
            uploadTime: e.uploadTime || e.createTime
          });
        } else {
          otherUploadIds.push({
            fileDesc: e.fileDesc,
            sn: i,
            uploadId: e.uploadId,
            uploadTime: e.uploadTime || e.createTime
          });
        }
      });
      return {
        gistUploadIds: gistUploadIds,
        otherUploadIds: otherUploadIds
      };
    },
    // sort 排序
    handleSort(property) {
      return function (a, b) {
        return a[property] - b[property];
      };
    },
    // 处理位数
    handleDecimal(val, decimal) {
      return val ? val.toFixed(decimal) : "";
    },
    handleTable(approvalStatus) {
      if (this.tableData.length) {
        let yunshu = [], // 运输类
          hebingqian = [], // 没有合并的数据
          hebinghou = [], // 合并后隐藏的数据
          hebingMerge = [], // 合并后生成的数据
          qita = []; // 其他类数据
        this.tableData.map(e => {
          if (e.isCategories && e.isCategories == 1) {
            if (approvalStatus == 3) {
              if (e.moneyWithTax != 0) yunshu.push(e);
            } else {
              yunshu.push(e);
            }
          } else if (
            e.isMerge == 0 &&
            e.isMainInventory == 0 &&
            e.isOtherCost == 0
          ) {
            hebingqian.push(e);
          } else if (
            e.isMerge == 1 &&
            e.isMainInventory == 0 &&
            e.isOtherCost == 0
          ) {
            hebinghou.push(e);
          } else if (
            e.isMerge == 1 &&
            e.isMainInventory == 1 &&
            e.isOtherCost == 0
          ) {
            hebingMerge.push(e);
          } else if (e.isOtherCost && e.isOtherCost == 1) {
            qita.push(e);
          }
        });
        this.showTableData = [
          ...hebingqian,
          ...hebingMerge,
          ...yunshu,
          ...qita
        ];
      } else {
        this.showTableData = [];
      }
    },
    // 合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr, rowIndex) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              if (column.label == "结算数量") {
                if (
                  data[rowIndex].isMerge == 1 &&
                  data[rowIndex].isMainInventory == 0
                ) {
                  return prev;
                }
                return new BigNumber(+prev).plus(+curr).toString();
              } else if (
                column.label == "含税金额" ||
                column.label == "不含税金额"
              ) {
                if (
                  data[rowIndex].isMerge == 1 &&
                  data[rowIndex].isMainInventory == 0
                ) {
                  return prev;
                }
                return new BigNumber(+prev).plus(+curr).toString();
              }
            } else {
              return (prev = " ");
            }
          }, 0);
          if (column.label == "结算数量") {
            sums[index] = (+sums[index]).toFixed(3);
          }
          if (column.label == "含税金额") {
            sums[index] = (+sums[index]).toFixed(2);
          }
        } else {
          sums[index] = "";
        }
      });
      return sums;
    },
    // 合计
    getSummaries1(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              if (
                column.label == "订单数量" ||
                column.label == "剩余可结算数量"
              ) {
                let num = new BigNumber(+prev).plus(+curr).toFixed(3);
                return num;
              }
            } else {
              return (prev = " ");
            }
          }, 0);
        } else {
          sums[index] = "";
        }
      });
      return sums;
    },
    handleBack() {
      this.$router.push("/settlement-management/material-rent-preserve/ListAll");
    }
  },
  activated() {
    this.activeName = "a";
    this.getList();
  },
  deactivated() {
    this.isTrue = false;
  }
};
</script>

<style scoped lang="scss">
/deep/ .el-table__fixed-header-wrapper {
  th {
    pointer-events: auto;
  }
}

/deep/ .el-table__fixed,
/deep/ .el-table__fixed-right {
  pointer-events: none;

  td {
    pointer-events: auto;
  }
}
</style>
